package com.coolwar.限流.计数器实现;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * 原子类计数器AtomicInteger、Semaphore信号量来做简单的限流
 *
 * @author Coolwar
 */
public class SampleSemaphore {

    /**
     * 原子类计数器
     */
    private final Semaphore semaphore = new Semaphore(10);
    /**
     * 起始时间
     */
    private long startTime = System.currentTimeMillis();

    public boolean check(int maxCount, long interval) throws InterruptedException {
        // 非阻塞(排他锁)
        boolean b = semaphore.tryAcquire();
        if (b) {
            return true;
        }
        // 超过了间隔时间，直接重新开始计数
        if (System.currentTimeMillis() - startTime > interval) {
            startTime = System.currentTimeMillis();
            semaphore.release(maxCount);
            return true;
        }
        // 还在间隔时间内,check有没有超过限流的个数
        return semaphore.availablePermits() > maxCount;
    }

    public static void main(String[] args) throws InterruptedException {
        SampleSemaphore sampleAtomicInteger = new SampleSemaphore();
        //限流的个数
        int maxCount = 10;
        //指定的时间内
        long interval = 5000;
        for (int i = 0; i < 100; i++) {
            boolean check = sampleAtomicInteger.check(maxCount, interval);
            Thread.sleep(new Random().nextInt(500));
            if (check) {
                System.out.println("通过：请求" + i);
            } else {
                System.out.println("限流中：请求" + i);
            }
        }

    }
}
